package cn.zf233.xcloud.web.socket;

import cn.zf233.xcloud.commom.R;
import cn.zf233.xcloud.util.JsonUtil;
import cn.zf233.xcloud.util.SpringUtil;
import cn.zf233.xcloud.web.AdminController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by zf233 on 2021/8/6
 * WebSocket 内存
 */
@Component
@ServerEndpoint("/socket/chart/memory")
public class MemoryChartSocket extends BaseSocket {

    private final Logger logger = LoggerFactory.getLogger(MemoryChartSocket.class);
    private static AdminController adminController;

    @PostConstruct
    public void init() {
        adminController = SpringUtil.getBean("adminController");
    }

    public void sendMessage(Session session) {
        try {
            while (session.isOpen()) {
                R<Map<String, Object>> r = adminController.get();
                session.getBasicRemote().sendText(JsonUtil.toJson(r));
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            logger.error("链接被关闭");
            logger.error(e.getMessage());
        }
    }
}